import axios from 'axios'
import Excel from 'exceljs'
import manifest from '../manifest'
import {Notify} from 'vant'
import qs from 'qs'
const licenseFile = require('nodejs-license-file');
// 设置超时时间
axios.defaults.timeout = 30 * 1000;
export const getCurrentTabId = (callback) => {
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    if (callback) callback(tabs.length ? tabs[0].id : null);
  });
}
export const sendMessageToContentScript = (message, callback) => {
  getCurrentTabId((tabId) => {
    if (tabId) {
      chrome.tabs.sendMessage(tabId, message, function (response) {
        if (callback) callback(response);
      });
    }
  });
}

/**
 * 导出
 * @param {*} data 
 * @param {*} fileName 
 */
export const exportExcel = async (data, fileName = '数据.xlsx') => {
  return new Promise(async (resolve) => {
    try {
      // 创建一个文件
      const workbook = new Excel.Workbook()
      const sheet = workbook.addWorksheet('数据')
      const tableRows = [
        {
          cardNumber: '卡号',
          pin: 'PIN',
          cardBalance: '余额',
          error: '状态',
        }
      ]
      tableRows.push(...data)
      // 设置默认行高
      sheet.properties.defaultRowHeight = 20;
      let columns = [{ key: 'cardNumber', width: 20 }, { key: 'pin', width: 10 }, { key: 'cardBalance', width: 10 }, , { key: 'error', width: 40 }]
      // 添加数据项定义
      sheet.columns = columns
      sheet.addRows(tableRows);
      sheet.getRow(1).height = 35;
      // 设置表头样式
      const colorHeader = '000000'
      const rowHeader1 = sheet.getRow(1)
      rowHeader1.eachCell((cell, rowNumber) => {
        cell.alignment = { vertical: 'middle', horizontal: 'center' }
        cell.font = { size: 12, family: 2, bold: true, color: { argb: 'ffffff' } }
        cell.fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: colorHeader }
        }
        cell.border = {
          top: { style: 'thin' },
          left: { style: 'thin' },
          bottom: { style: 'thin' },
          right: { style: 'thin' }
        }
      })

      // 冻结行
      sheet.views = [{
        state: 'frozen', ySplit: 1, activeCell: 'A1'
      }]

      const buffer = await workbook.xlsx.writeBuffer()
      download(buffer, fileName)
      resolve(true)
    } catch (e) {
      console.log(e)
      resolve(false)
    }
  })
}
export const download = (_blob, filename) => {
  const blob = new Blob([_blob])
  const downloadElement = document.createElement('a')
  downloadElement.style.display = 'none'
  const href = window.URL.createObjectURL(blob) // 创建下载的链接
  downloadElement.href = href
  downloadElement.download = filename // 下载后文件名
  document.body.appendChild(downloadElement)
  downloadElement.click() // 点击下载
  document.body.removeChild(downloadElement) // 下载完成移除元素
  window.URL.revokeObjectURL(href) // 释放掉blob对象
}

export const getBase64Image = (img) => {
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0, img.width, img.height);
  var dataURL = canvas.toDataURL("image/png");
  return dataURL
}

/**
 * 查询用户
 * @param {*} page 
 * @returns 
 */
export const fetchUser =  (header) =>  axios.get(
  `https://www.walmart.com/orchestra/home/graphql/accountLandingPage/4a906799bb64ea93fe88be278e93fe58284d48fd0d144565ea287400f6cf0942?variables=%7B%22enablePhoneCollection%22%3Afalse%7D`, 
  {
  headers: 
    {
      "x-o-platform-version":"us-web-1.98.0-835f67b-0907T1705",
      "x-o-gql-query":"query accountLandingPage",
      "WM_PAGE_URL":"https://www.walmart.com/account",
      "X-APOLLO-OPERATION-NAME":"accountLandingPage",
      "x-o-bu":"WALMART-US",
      "x-o-platform":"rweb","x-o-segment":"oaoh",
      "Content-Type":"application/json","accept":"application/json",
      "x-enable-server-timing":"1","x-o-ccm":"server",
      // "wm_qos.correlation_id":"0jcYYjFw6Q8dgVsLvpzNd2XBN8xB1GjcyYjh",
    }
  })

  function generateRandomPlatformVersion(appName, buildIdLength = 16) {
    const majorVersion = Math.floor(Math.random() * 10) + 1; // 随机生成 1 到 10 的主版本号
    const minorVersion = Math.floor(Math.random() * 1000); // 随机生成 0 到 999 的次版本号
    const revision = Math.floor(Math.random() * 10); // 随机生成 0 到 9 的修订号
    const buildId = generateRandomBuildId(buildIdLength); // 随机生成构建标识
  
    const versionString = `${majorVersion}.${minorVersion}.${revision}`;
    const platformVersion = `${appName}-${versionString}-${buildId}`;
  
    // 可以添加其他前缀或后缀，例如："x-o-platform-version"
    return platformVersion;
  }
  
  function generateRandomBuildId(length) {
    const characters = "abcdefghijklmnopqrstuvwxyz0123456789";
    let buildId = "";
    for (let i = 0; i < length; i++) {
      const randomIndex = Math.floor(Math.random() * characters.length);
      buildId += characters.charAt(randomIndex);
    }
    return buildId;
  }
  
/**
 * 查询礼品卡余额
 * @param {*} page 
 * @returns 
 */
export const fetchGiftCard =  (cardNumber, pin) => {
  let version = generateRandomPlatformVersion('us-web')
  return axios.post(
    `https://www.walmart.com/orchestra/home/graphql`, 
    {
      "query":"query GuestGiftCardBalance($cardNumber:String! $pin:String!){giftCardBalance(input:{cardNumber:$cardNumber pin:$pin}){cardBalance}}",
      "variables":{"cardNumber": cardNumber,"pin": pin}
    },
    {
    headers: 
      {
        "ldy": "1",
        "x-o-platform-version": version,
        "x-o-gql-query":"query GuestGiftCardBalance",
        // "WM_PAGE_URL":"https://www.walmart.com/account",
        "X-APOLLO-OPERATION-NAME":"GuestGiftCardBalance",
        "x-o-bu":"WALMART-US",
        "x-o-platform":"rweb","x-o-segment":"oaoh",
        "Content-Type":"application/json","accept":"application/json",
        "x-enable-server-timing":"1","x-o-ccm":"server",
        // "wm_qos.correlation_id":"0jcYYjFw6Q8dgVsLvpzNd2XBN8xB1GjcyYjh",
      }
    })
}  


//   /**
//  * 查询礼品卡余额
//  * @param {*} page 
//  * @returns 
//  */
// export const fetchGiftCard =  (cardNumber, pin) =>  axios.post(
//   `https://www.walmart.com/orchestra/home/graphql/CreateAccountGiftCard/10c28fc94ce45b7e08ddcf042a9f280d76698ab6e3d5b20d4e57065efa64c5bb`, 
//   {
//     "variables":{"input":{"cardNumber": `${cardNumber}`,"pin": `${pin}`,"displayLabel":""}}
//   },
//   {
//   headers: 
//     {
//       "x-o-platform-version":"us-web-1.98.0-835f67b-0907T1705",
//       "x-o-gql-query":"mutation CreateAccountGiftCard",
//       "WM_PAGE_URL":"https://www.walmart.com/account",
//       "X-APOLLO-OPERATION-NAME":"CreateAccountGiftCard",
//       "x-o-bu":"WALMART-US",
//       "x-o-platform":"rweb","x-o-segment":"oaoh",
//       "Content-Type":"application/json","accept":"application/json",
//       "x-enable-server-timing":"1","x-o-ccm":"server",
//       // "wm_qos.correlation_id":"0jcYYjFw6Q8dgVsLvpzNd2XBN8xB1GjcyYjh",
//     }
//   })
/**
 * 删除礼品卡
 * @param {*} page 
 * @returns 
 */
export const delGiftCard =  (id) =>  axios.post(
  `https://www.walmart.com/orchestra/home/graphql/DeleteAccountPayments/600d14984badeea49b44044d6c361b2596bf0df649a721015a2ee894e1ec75e8`, 
  {
    "variables":{"id": id}
  },
  {
  headers: 
    {
      "x-o-platform-version":"us-web-1.98.0-835f67b-0907T1705",
      "x-o-gql-query":"mutation DeleteAccountPayments",
      "WM_PAGE_URL":"https://www.walmart.com/account",
      "X-APOLLO-OPERATION-NAME":"DeleteAccountPayments",
      "x-o-bu":"WALMART-US",
      "x-o-platform":"rweb","x-o-segment":"oaoh",
      "Content-Type":"application/json","accept":"application/json",
      "x-enable-server-timing":"1","x-o-ccm":"server",
      // "wm_qos.correlation_id":"0jcYYjFw6Q8dgVsLvpzNd2XBN8xB1GjcyYjh",
    }
  })



const template = [
  '====BEGIN LICENSE====',
  '{{&licenseVersion}}',
  '{{&applicationName}}',
  '{{&applicationVersion}}',
  '{{&type}}',
  '{{&email}}',
  '{{&expirationDate}}',
  '{{&serial}}',
  '=====END LICENSE====='
].join('\n');

let publicKey = `
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArwxCeNqlkJNFC+XJZwVd
xUhpsNG77hxX05fG9hKIir7OmAgvMeHc9JjQEqRUsSkv1MIeg8T5O1577Gu9d8us
Jt5bG5ggCzVX3ErpkOozKKGVeL4kFGo4RVR1UmJsBAQwoI5jXR0FvRJ54iGAnx3N
DjPTxOxgcjfCuzmVxiyLLxykueNXwJexBU3U38I9AnbLZwYiZl4LTrhQR7+rvwPy
jIUOO9NYm8J5ehcFr8nrqXxJWRCu9aGvhohkxmC/8as9SZ2Qyzm2jYC5SYd92kLs
1ekoIW5XjU9y/KFkQIsVENUFYAV3gj5XJlePdSR+iGAE/2ygX2+d1wmOVBQCYx3A
IwIDAQAB
-----END PUBLIC KEY-----
`
export const loadFile = () => {
  return new Promise(async resolve => {
    let data = []
    data.push('====BEGIN LICENSE====')
    let url = chrome.runtime.getURL('license.json')
    console.log('url', url)
    let license = await axios.get(url).then(res => {
      console.log('data==', res)
      if (res.status === 200) {
        return res.data
      }
      return false
    })
    if (!license) {
      console.log('授权错误：授权文件不存在')
      resolve(false)
      return ''
    }
    data.push(license.licenseVersion)
    data.push(license.applicationName)
    data.push(license.applicationVersion)
    data.push(license.type)
    data.push(license.email)
    data.push(license.expirationDate)
    data.push(license.serial)
    data.push('=====END LICENSE=====')
  
    if (new Date(license.expirationDate) < new Date()) {
      console.log('授权错误：已过有效期', license.expirationDate)
      Notify('授权错误：已过有效期')
      resolve(false)
      return ''
    }
    resolve(data.join('\n'))
    return
  })
  
}

export const valid = () => {
  return new Promise(async resolve => {
    try {
      let lic = await loadFile()
      if (!lic) {
        resolve(false)
        return
      }
      console.log('lic', lic)
      const data = licenseFile.parse({
        publicKey: publicKey,
        licenseFile: lic,
        template
      });
      if (data.data.applicationVersion !== manifest.version) {
        console.log('版本错误')
        Notify('软件授权版本错误')
        return false
      }
      if (data.data.applicationName !== manifest.name) {
        console.log('授权应用名称错误')
        Notify('授权应用名称错误')
        resolve(false)
        return
      }
      console.log(data);
      resolve(data.valid)
    } catch (err) {
      console.log(err);
      resolve(false)
      return
    }
  })
}